package monster.comm.util;

import javax.servlet.ServletContext;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.FileSystemXmlApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import monster.comm.log.ILog;
import monster.comm.log.LogService;

/**
 * 启动系统时候就初始化这个类，加载spring 配置文件
 * 可以在不启动服务器情况下访问bean
 * @author jzk
 * @version 1.0
 */
public class SpringApplicationContextFactory {

	private static ILog log = LogService
			.getLog(SpringApplicationContextFactory.class);

	private static ApplicationContext ctx = null;

	private static String beanFileNames[] = new String[] {"classpath*:monster/commcfg/spring_*.xml",
		"classpath*:monster/dsch/comm/cfg/spring/*.xml",
		"classpath*:monster/dsch/admin/cfg/spring/*.xml" };

	/**
	 * 通过FileSystemXmlApplicationContext取得xml文件 beanFileName[]
	 * 文件的地址加文件名eg:springcfg/bean.xml的数组 主要用于运用的多个bean.xml的加载
	 * 
	 * @return ApplicationContext
	 * @throws Exception
	 */
	public synchronized static ApplicationContext getApplicationContex_noWeb()
			throws Exception {

		if (null == ctx) {
			ctx = new FileSystemXmlApplicationContext(beanFileNames);
		}
		return ctx;
	}

	/**
	 * 在B/S模式下面得到这个方法在监听器里面设置
	 * 
	 * @param c
	 */
	public static void setApplicationContext(ServletContext c) {

		if (null == ctx) {
			ctx = WebApplicationContextUtils.getWebApplicationContext(c);
		}

	}

	/**
	 * 设置beanFile
	 * 
	 * @param beanFileNames
	 *            String[]
	 */
	public static void setBeanFileNames(String[] beanFileNames) {

		SpringApplicationContextFactory.beanFileNames = beanFileNames;
	}

	public static void closeApplication() {

		if (null != ctx) {
			ctx = null;
			log.info("/*********注销掉spring的ApplicationContext********/");
		}

	}

	/**
	 * 得到一个对象
	 * 
	 * @param serviceName
	 * @return Object
	 * @throws Exception
	 */
	public static Object getService(String serviceName) throws Exception {

		if (null == ctx) {
			ctx = getApplicationContex_noWeb();
		}
		if (null == ctx) {
			throw new Exception("没有得到spring的ApplicationContex");
		}
		return ctx.getBean(serviceName);
	}
   public static void main(String[] args){
	   try {
		System.out.println(SpringApplicationContextFactory.getService("dataSource").getClass().getName());
	} catch (Exception e) {
		e.printStackTrace();
	}
	   
   }
}
